package com.lbs.jiepiaisi.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.EquipSearchActivity;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.bean.EquipBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.utils.AggregationUtils;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant1;
import com.lbs.jiepiaisi.utils.DialogUtil;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.SpUtil;
import com.lbs.jiepiaisi.utils.WindowSizeUtil;
import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment implements AMap.OnMyLocationChangeListener{

    private TextureMapView mMapView;//地图
    private AMap aMap;//地图控制器对象

    private String tempDeptId = "";
    private String childDeptId = "";
    private int size = 1000;
    private LatLng locationLatLng;//当前手机定位位置
    List<EquipBean.Result.Items> itemList = new ArrayList<>();
    private AggregationUtils aggregationutils;
    private LatLng bjLatLng = new LatLng(39.894914,116.322062);//北京经纬度
    private float mMapPositionZoom;

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        mMapView.onSaveInstanceState(bundle);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //需要放在onResume的方法放在该处执行
            childDeptId = (String) SpUtil.get(Constant1.UNDERLING_DEPTID,"");

            Log.e("eee999",childDeptId+"");
            Log.e("eee999",tempDeptId+"");

            if (!tempDeptId.equals(childDeptId)) {
                page = 1;
                itemList.clear();
                loadData();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home,null);
        mMapView = view.findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setOnMyLocationChangeListener(this);
        }

        aggregationutils = new AggregationUtils();
        aggregationutils.setaMap(aMap, mMapView, itemList);
        aggregationutils.setContext(mContext);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bjLatLng,3));

        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.point4));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

        view.findViewById(R.id.ll_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ButtonUtil.isFastClick()){
                    Intent intent = new Intent(mContext,EquipSearchActivity.class);
                    startActivityForResult(intent,1000);
                    //IntentUtil.gotoActivity(mActivity, EquipSearchActivity.class, false);
                }
            }
        });

        view.findViewById(R.id.btn_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ButtonUtil.isFastClick()){
                    if(locationLatLng != null){
                        //poiOverlay.zoomToSpan();
                        Log.e("我的位置","我的位置");
                        mMapPositionZoom = 16.f;
                        moveMapToPosition(locationLatLng);
                    }
                }
            }
        });

        DialogUtil.show(mContext,"正在加载中");

        return view;
    }

    private void moveMapToPosition(LatLng latLng) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(
                new CameraPosition(
                        latLng,//新的中心点坐标
                        mMapPositionZoom,    //新的缩放级别
                        0,    //俯仰角0°~45°（垂直与地图时为0）
                        0     //偏航角 0~360° (正北方为0)
                ));
        aMap.animateCamera(cameraUpdate,300, new AMap.CancelableCallback() {
            @Override
            public void onFinish() {}

            @Override
            public void onCancel() {}
        });
    }

    public void loadData() {
        Api.getInstance().createService()
                .loadEquipList(childDeptId,page,size,"","")
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<EquipBean>(mContext,false) {
                    @Override
                    public void onSuccess(EquipBean result) {
                        List<EquipBean.Result.Items> it = result.getResult().get(0).getItems();
                        Log.e("777888", "查询车辆信息000：" + result.getResult().get(0).getItems().size());

                        for (int i = 0; i < it.size(); i++) {
                            //Log.e("777888", "查询车辆信息111：" + it.get(0).getPoint().getLat());
                            //Log.e("777888", "查询车辆信息44444：" + it.get(i).getPoint().getLat());
                            if (it.get(i).getPoint() != null
                                    && it.get(i).getPoint().getLat() != null && it.get(i).getPoint().getLng() != null && !it.get(i).getPoint().equals("null")) {
                                if (!it.get(i).getMark().equals("D")) {
                                    itemList.add(it.get(i));
                                }
                            }
                        }

                        if (it.size() >= 1000) {
                            page++;
                            loadData();
                        } else {
                            DialogUtil.dismiss();
                            List<AggregationUtils.ClusterItem> allPoints = new ArrayList<>();
                            for (int i = 0; i < itemList.size(); i++) {
                                AggregationUtils.ClusterItem ac = new AggregationUtils.ClusterItem();
                                ac.latLng = new LatLng(itemList.get(i).getPoint().getLat(), itemList.get(i).getPoint().getLng());
                                ac.address = i + "";
                                ac.id = i + "";
                                allPoints.add(ac);
                            }
                            aggregationutils.clearMarkers();
                            aggregationutils.setAllPoints(allPoints);
                            aggregationutils.showPoint();

                            tempDeptId = (String) SpUtil.get(Constant1.UNDERLING_DEPTID, "");
                        }
                    }

                    @Override
                    public void onFailure(ErrorException e) {

                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 1000) {
            Bundle bundle = data.getExtras();
            EquipBean.Result.Items item = (EquipBean.Result.Items)bundle.getSerializable("item");
            //aMap.moveCamera(CameraUpdateFactory.zoomTo(19));
            mMapPositionZoom = 19.0f;
            LatLng latLng = new LatLng(item.getPoint().getLat(),item.getPoint().getLng());
            moveMapToPosition(latLng);
            aMap.setPointToCenter(WindowSizeUtil.getWidth(mContext) / 2, WindowSizeUtil.getHeight(mContext) / 5 * 4);
        }
    }

    /** 回调方法获取经纬度信息*/
    public void onMyLocationChange(android.location.Location location){
        Log.i("定位蓝点位置信息回调：","latitude = "+location.getLatitude());
        if (location != null) {
            //mListener.onLocationChanged(location);
            locationLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        }
    }

    @Override
    public View initView(LayoutInflater inflater) { return null; }
    @Override
    protected void getExtras(View view) { }
    @Override
    protected void findView(View view) { }
    @Override
    protected void setListener(View view) { }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }
}
